package com.fw.ui.view.settings.usercontrol.merchantuser.event;

import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.fw.service.bean.EntryBean;
import com.fw.ui.bao.MasterDataBAO;
import com.fw.ui.bao.PropertyBAO;
import com.fw.ui.util.VaadinApplicationObjectSupport;
import com.fw.ui.view.event.AbstractListener;
import com.fw.ui.view.settings.usercontrol.merchantuser.CreateMerchantUserView;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;

@Component
@Scope(SCOPE_PROTOTYPE)
public class CreateMerchantUserMerchantValueChangeListener extends AbstractListener implements ValueChangeListener {

    private static final long serialVersionUID = 1L;

    @Autowired
    protected transient VaadinApplicationObjectSupport app;
    @Autowired
    private PropertyBAO propertyBAO;

    @Autowired
    private MasterDataBAO masterDataBAO;

    @Override
    public void valueChange(ValueChangeEvent event) {

	CreateMerchantUserView createMerchantUserView = (CreateMerchantUserView) this.getBasedComponent();
	createMerchantUserView.getCbbService().setReadOnly(false);
	createMerchantUserView.getCbbService().removeAllItems();
	Long merchantId = (Long) event.getProperty().getValue();
	if (merchantId != null) {
	    String merchantID = (String) createMerchantUserView.getCbbMerchant().getItemCaption(merchantId);
	    if (merchantID != null && !merchantID.isEmpty()) {
		try {
		    List<EntryBean<Long, String>> serviceProfileItems = masterDataBAO.selectAllMerchantUserServiceProfile(merchantID);
		    if (serviceProfileItems != null) {
			for (EntryBean<Long, String> entry : serviceProfileItems) {
			    createMerchantUserView.getCbbService().addItem(entry.getKey());
			    createMerchantUserView.getCbbService().setItemCaption(entry.getKey(), entry.getValue());
			}
		    }
		} catch (Exception e) {
		    e.printStackTrace();
		}
	    }
	}
    }
}
